import os

from pydub import AudioSegment
from pydub.silence import split_on_silence

class Worker(object):
    def __init__(self):
        print("tooles.common.spliter")

    def split(self, fn, format, duration):
        audio = AudioSegment.from_file(fn, format)
        chunks = split_on_silence(audio, min_silence_len=1000, silence_thresh=-40, keep_silence=1000)
        # 合并相邻的短音频片段
        combined_chunks = []
        current_chunk = chunks.pop(0)
        for chunk in chunks:
            if len(current_chunk) + len(chunk) <= duration:  # 如果合并后的长度小于5分钟
                current_chunk += chunk
            else:
                combined_chunks.append(current_chunk)
                current_chunk = chunk
        combined_chunks.append(current_chunk)  # 添加最后一个音频片段
        # 保存每个音频片段
        for i, chunk in enumerate(combined_chunks):
            chunk.export(f"output_chunk_{i}.mp3", format="mp3")
        print("音频分割完成!")

    def spleeter(self, fn, outpath):
        os.system(f"spleeter separate -p spleeter:2stems {fn} -o {outpath}")

if __name__ == "__main__":
    worker = Worker()
    # res = worker.split("test1.wav", "wav", 6 * 60 * 1000)
    # print(res)
    worker.spleeter("test1.wav","xx")